package com.psj.controller;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.jwt.JWT;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.psj.bean.User;
import com.psj.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.swing.plaf.PanelUI;
import java.util.Date;
import java.util.HashMap;

@Controller
@RequestMapping("user")
public class UserController {

    @Autowired
    UserService userService;

    @RequestMapping("toLogin")
    public String toLogin(Model model){
        model.addAttribute("user",new User());
        return "login";
    }

    @RequestMapping("login")
    public String login(@Validated User user, BindingResult result, HttpServletResponse response, Model model){
        if(result.hasErrors()){
            return "login";
        }

        User userDB = userService.getByName(user.getUsername());
        if(null==userDB){
            model.addAttribute("error","该用户不存在");
            return "login";
        }
        String pwd = userDB.getPwd();
        String pwd1 = user.getPwd();
        if(!pwd.equals(pwd1)){
            result.rejectValue("pwd","","密码输入错误");
            return "login";
        }

        String token = JWT.create()
                .setPayload("username", userDB.getUsername())
                .setPayload("id", userDB.getId())
                .setKey(key)
                .setExpiresAt(DateUtil.offset(new Date(),DateField.MINUTE,30))
                .sign();
        Cookie cookie = new Cookie("login_token",token);
        cookie.setPath("/");
        cookie.setMaxAge(30*60);
        response.addCookie(cookie);

        return "redirect:/list";
    }

    // 密钥
    byte[] key = "1234567890".getBytes();


    @RequestMapping("auth")
    public String auth(String code,HttpServletResponse response){
        //?=&code={}&
        // client_id={client_id}&={redirect_uri}&={client_secret}
        String url = "https://gitee.com/oauth/token";
        //POST请求
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("grant_type", "authorization_code");
        paramMap.put("code", code);
        paramMap.put("client_id", "43d6f3c9dc78fb8e4d6a028a5fa1ead139e825ba4df8154b20f5e5b1eeb451ba");
        paramMap.put("redirect_uri", "http://localhost:8080/user/auth");
        paramMap.put("client_secret", "8f11ab9b878de31cc8c223a25ff3c295c8c8e2a77fcd4d148e01883ba6bb4c30");

        String access_token = HttpUtil.post(url, paramMap);
        JSONObject jsonObject = JSON.parseObject(access_token);
        Object token = jsonObject.get("access_token");

        String url2 = "https://gitee.com/api/v5/user?access_token="+token;
        String s = HttpUtil.get(url2);
        JSONObject jsonObject1 = JSON.parseObject(s);
        String username = (String) jsonObject1.get("name");

        User userDB = userService.getByName(username);
        if(null==userDB){
            userDB = new User();
            userDB.setUsername(username);
            userService.addUser(userDB);
        }

        String jwtToken = JWT.create()
                .setPayload("username", userDB.getUsername())
                .setPayload("id", userDB.getId())
                .setKey(key)
                .setExpiresAt(DateUtil.offset(new Date(),DateField.MINUTE,30))
                .sign();
        Cookie cookie = new Cookie("login_token",jwtToken);
        cookie.setPath("/");
        cookie.setMaxAge(30*60);
        response.addCookie(cookie);

        return "redirect:/list";
    }


}
